package com.timerecording.service.login.captcha;

import com.timerecording.domain.vo.login.CaptchaVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.RandomUtil;
import java.util.UUID;
import java.awt.*;

/**  获取图形验证码
 * @author smz41
 * @description: TODO
 * @date 2025/1/26
 */

@Service
@Slf4j
public class CaptchaService {

    public static final long EXPIRE_SECOND = 65L;

    //空字符串
    public static final String EMPTY = "";


    /** 获取验证码  默认一分钟有效
     * @description: TODO
     * @author smz
     * @version 1.0
     * @date 2025/1/26
     */

    public CaptchaVO generateCaptcha(){
        //生成四位验证码
        String captchaText = RandomUtil.randomNumbers(4);

        //定义图形验证码的长、宽、验证码位数、干扰线数量
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(125, 43, 4, 80);

        //设置背景颜色
        lineCaptcha.setBackground(new Color(230, 244, 255));

        //生成图片
        Image image = lineCaptcha.createImage(captchaText);

        //转为base64
        String base64Code = ImgUtil.toBase64(image, "jpg");

        /*
         * 返回验证码对象
         * 图片 base64格式
         */
        // uuid 唯一标识
        String uuid = UUID.randomUUID().toString().replace("-", EMPTY);

        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaUuid(uuid);
        captchaVO.setCaptchaBase64Image("data:image/png;base64," + base64Code);
        captchaVO.setExpireSeconds(EXPIRE_SECOND);
        //TODO  将验证码存入redis，由于正式服务器中没有redis服务,省略
        /*if (!systemEnvironment.isProd()) {
            captchaVO.setCaptchaText(captchaText);
        }
        String redisCaptchaKey = redisService.generateRedisKey(RedisKeyConst.Support.CAPTCHA, uuid);
        redisService.set(redisCaptchaKey, captchaText, EXPIRE_SECOND);*/
        return captchaVO;

    }



}
